import basic
import re
from bs4 import BeautifulSoup as bs
from urllib import parse


class CommitTeacher(basic.JwcMain):
    def getEntrance(self, soup):
        tags = soup(href=re.compile("xsjxpj.aspx?"))
        alist = [parse.urljoin(self.mainPageUrl, tag['href']) for tag in tags]
        if not alist:
            raise basic.JwcMain.NotAble
        self.functionPage = alist[0]
        reg = re.compile("xsjxpj.aspx\?xkkh=(.+?)&")
        self.courseCode = [reg.search(url).group(1) for url in alist]

    def postsave(self, specific=None, default ="优秀", submit = True):
        if specific is None:
            specific = {}
        response = self.get(self.functionPage)
        for courseCode in self.courseCode:
            soup = bs(response.text, 'html5lib')
            courseName = soup.find(id='pjkc').find(selected='selected').text
            print(courseName)
            teacherName = soup.find(class_='datagridhead').find_all('td')[3].text
            commit = ''
            for key in specific:
                if re.search(key, courseName) or re.search(key, teacherName):
                    commit = specific[key]
                    continue
            if not commit: commit = default
            selectNum = len(soup('select'))
            viewstate = soup.find(attrs={'name': '__VIEWSTATE'})['value']
            param = [
                ('__EVENTTARGET', ''),
                ('__EVENTARGUEMENT', ''),
                ('__VIEWSTATE', viewstate),
                ('pjkc', courseCode),
                ('pjxx', ''),
                ('txt1', ''),
                ('TextBox1', ''),
                ('Button1', '保  存')
            ]
            param2 = [('DataGrid1:_ctl' + str(i) + ':JS1', commit) for i in range(2, selectNum + 1)]
            param[4:4] = param2
            response = self.post(self.functionPage, param, True)
        if submit:
            param[-1] = ('Button2', '提  交')
            self.post(self.functionPage, param, True)


    def __init__(self):
        super(CommitTeacher, self).__init__()



a = CommitTeacher()
a.postsave({'写作': '良好'},'优秀')